Skip to content

API Interface Design ​

This document is based on the following source files:

  • internal/app/routers.go -- complete route registration (Chi v5 routing tree)
  • internal/handlers/response.go -- response helper functions (respondJSON / respondError)
  • internal/handlers/*.go -- the various business Handler definitions and Swagger annotations
  • internal/middleware/auth.go -- JWT authentication middleware (Bearer + query param)
  • internal/jsplugin/routes.go -- JS plugin static/API route registration
  • docs/api_response.md -- API response format specification
  • AGENTS.md -- API documentation conventions + config interface conventions (hard rules)

Table of Contents ​

  1. Design Principles
  2. Response Format Specification
  3. Route Organization Structure
  4. Authentication Mechanism
  5. Handler Creation Pattern
  6. Comparison of the Three Config Interfaces
  7. Swagger Documentation Specification
  8. Complete Route List

1. Design Principles ​

Section sources: docs/api_response.md, AGENTS.md (backend coding conventions)

The Songloft backend API follows these core principles:

  • RESTful direct return: successful responses return the business model or collection directly, without a unified {code, data, message} envelope. The HTTP status code carries the semantics; a code field duplicating it is redundant.
  • Unified error format: error responses from all JSON API endpoints are uniformly {"error": "...", "detail": "..."}; using alternative field names such as message, msg, or reason is forbidden.
  • Resource-oriented paths: URL paths use plural nouns to represent resource collections (/songs, /playlists), and HTTP methods express the operation semantics (GET to read, POST to create, PUT to modify, DELETE to delete).
  • Standardized pagination: list endpoints paginate via the limit + offset query parameters, and responses include total, limit, and offset metadata.
  • Binary stream exception: errors from binary-stream endpoints such as play (/songs/{id}/play), proxy (/proxy), and static files may use plaintext http.Error(), since the client does not expect a JSON body.

2. Response Format Specification ​

Section sources: internal/handlers/response.go, docs/api_response.md

2.1 Response Helper Functions ​

All handlers output success responses via respondJSON(w, status, data) (data is serialized directly as top-level JSON) and output errors via respondError(w, status, message, err) (which automatically builds {"error","detail"}). The middleware layer uses a separate respondAuthError with a consistent format.

2.2 Three Forms of Success Response ​

ScenarioFormatExample
Single entityModel serialized directly{"id":1, "title":"Track", ...}
Paginated listCollection name + pagination metadata{"songs":[...], "total":100, "limit":20, "offset":0}
Operation resultMessage string{"message": "Song deleted"}

2.3 Error Response Format ​

json
{
  "error": "Human-readable error message",
  "detail": "Optional low-level technical detail"
}
  • error -- always present, a short user-facing description
  • detail -- optional, output only when err != nil, containing the low-level error information

Corresponds to the models.ErrorResponse struct; custom field names are forbidden.


3. Route Organization Structure ​

Section sources: internal/app/routers.go, internal/jsplugin/routes.go

3.1 Routing Tree Overview ​

Route registration is split into three layers, orchestrated uniformly by App.setupRouter():

chi.Router (root)
├── Global middleware: Compress → Logger → Recoverer → RequestID → CORS
├── Frontend static files / Swagger (dev build)
├── /api/v1 ─┬─ [Public] /auth/login, /auth/refresh, /version, /health
│            └─ [Bearer] /auth/*, /songs/*, /playlists/*, /settings/*,
│                        /configs/*, /scan/*, /cache-manage/*, /upgrade/*, /proxy
├── /api/v1/jsplugins/* [Bearer] plugin CRUD + registry + /plugins/health
├── /api/v1/jsplugin/{entryPath}[/static/*] [Public] plugin static assets
├── /api/v1/jsplugin-assets/* [Public] common CSS/JS/fonts
└── /api/v1/jsplugin/{entryPath}/* [Bearer+PublicPathChecker] API forwarding

3.2 Middleware Stack ​

Global middleware is registered in setupBaseRouter(), in execution order: Compress(Gzip) -> RequestLogger(slog) -> Tracely(panic reporting) -> Recoverer(500) -> RequestID -> CORS -> CORP. The authentication middleware AuthMiddleware is not global middleware; it is added on demand inside each route group.

3.3 Route Grouping Strategy ​

Chi v5's r.Group() divides authentication boundaries: under the same /api/v1 prefix, public endpoints are registered directly, while authenticated endpoints are wrapped by r.Group + r.Use(AuthMiddleware). JS plugin routes are registered separately; static assets require no authentication, and API forwarding supports the PublicPathChecker interface to exempt plugin-declared public paths.


4. Authentication Mechanism ​

Section sources: internal/middleware/auth.go

4.1 JWT Dual-Token Mechanism ​

The system uses JWT dual-token authentication:

  • Access Token -- short-lived, used for API request authentication
  • Refresh Token -- long-lived, used to refresh the access token

4.2 Token Passing Methods ​

The authentication middleware tries two methods, in priority order, to obtain the token:

  1. Authorization Header (priority): Authorization: Bearer <token>
  2. Query Parameter (fallback): ?access_token=<token>

The query parameter fallback mainly serves scenarios where a custom header cannot be set: <img> tags loading cover art, <audio> tags loading audio, CachedNetworkImage, etc.

4.3 Public Endpoints ​

The following endpoints require no authentication and are registered directly outside the AuthMiddleware:

EndpointPurpose
POST /api/v1/auth/loginUser login
POST /api/v1/auth/refreshRefresh token
GET /api/v1/versionVersion information
GET /api/v1/healthHealth check
GET /api/v1/jsplugin/{entryPath}Plugin static page
GET /api/v1/jsplugin/{entryPath}/static/*Plugin static assets
GET /api/v1/jsplugin-assets/*Plugin common assets

In addition, API paths declared by a plugin via publicPaths in its manifest are exempted by the PublicPathChecker interface inside the authentication middleware.


5. Handler Creation Pattern ​

Section sources: internal/handlers/*.go, internal/app/routers.go

5.1 Factory Function Pattern ​

Each Handler follows a three-step creation: (1) a struct holding service dependencies; (2) a NewXxxHandler(...) factory function that receives services and returns a pointer; (3) an optional SetXxx(fn) setter to resolve circular dependencies or deferred binding. Taking SongHandler as an example, the factory function receives 6 dependencies such as SongService, CacheService, and AsyncReassigner, and after creation injects the Scanner's path-getter function via SetGetMusicPath.

5.2 Handler List ​

The main Handlers are located in internal/handlers/:

  • Business core: AuthHandler(AuthService), SongHandler(SongService + CacheService + 4 dependencies), PlaylistHandler(PlaylistService), BackupHandler(BackupService)
  • Config management: ConfigHandler(ConfigService), ScanHandler(SongService + Scanner + ConfigService), HLSHandler(SongService + ConfigService), CacheHandler(CacheService + ConfigService), LogHandler(ConfigService + LevelVar)
  • Plugin/upgrade: JSPluginHandler(PackageManager + Repository + Manager + SourceMetrics + ConfigService), UpgradeHandler(UpgradeService)
  • Utility: ProxyHandler(no dependencies), VersionHandler(no dependencies), HealthHandler(no dependencies)

5.3 Callback Injection ​

Some handlers bind cross-module callbacks via setters: configHandler.SetOnConfigChanged triggers side effects after a generic KV write, scanHandler.SetOnMusicPathChanged / SetOnAutoScanChanged bind rebuild logic after config changes, and songHandler.SetGetMusicPath lazily injects the Scanner's path function.


6. Comparison of the Three Config Interfaces ​

Section sources: AGENTS.md (config interface conventions, hard rules), internal/app/routers.go

Three config interface styles exist in the project, each with a clear division of labor:

Dimension/settings/<name>/<module>/config/configs/{key}
PositioningBusiness feature toggle (user-facing)Module aggregate configadmin generic KV editing
Path style/settings/<kebab-case>/<module>/config/configs/{key}
Data formStrongly typed JSONStrongly typed JSON{key, value} string
Default valueHandled internally by the handlerHandled internally by the handlerNone (returns 404 if the key does not exist)
Side effectsTriggered directly inside PUTTriggered directly inside PUTRequires an onConfigChanged callback
OwnershipCorresponding business module handlerModule handlerConfigHandler
Use caseIsolated config or cross-module sharingStrongly related to module action endpointsadmin debugging / hand-editing

6.1 Business Endpoints /settings/<name> ​

Business settings cover scanning, playback, plugins, logging and client preferences. See internal/app/routers.go and the backend endpoint overview for current paths. Responses are typed JSON such as {enabled: bool} or {proxy: string}; handlers own defaults and side effects.

6.2 Module Aggregate Endpoints ​

A typical example is cache management /cache-manage/*, where config (GET/PUT) shares the prefix and CacheService with stats, clean, and validate-dir. Applicable to scenarios where config is strongly related to module action endpoints.

6.3 Generic KV /configs/{key} ​

Used only by the frontend generic config editor (admin hand-editing); no strong typing, no side effects (unless an onConfigChanged callback is attached), and PUT returns 404 when the key does not exist. New business features are forbidden from calling it directly.

6.4 Dual-Entry Consistency ​

Some config is modified by both a business endpoint and generic KV (such as music_path). The musicPathChanged closure in routers.go ensures both entries share the same side-effect function -- the business endpoint triggers it directly inside the PUT handler, and generic KV triggers it via the onConfigChanged callback.


7. Swagger Documentation Specification ​

Section sources: AGENTS.md (API documentation conventions, hard rules)

7.1 Hard Rules ​

Every handler method registered in routers.go must have swag annotations. No exemptions.

7.2 Required Fields ​

Each handler contains at least the following 7 swag annotations:

FieldDescription
@SummaryA one-line summary in Chinese
@DescriptionDetailed description (side effects/defaults/error-code triggers)
@TagsBusiness grouping (in Chinese), reusing existing tags
@ProduceResponse format (usually json)
@SuccessSuccess response type and description
@SecurityBearerAuth (omitted for public endpoints)
@RouterPath and method

Endpoints with a request body additionally add @Accept json and @Param request body.

7.3 Existing Business Tags ​

歌曲管理 | 歌单管理 | 电台与 HLS | 扫描管理 | 配置管理
缓存管理 | JS插件管理 | JS 插件 | 数据备份 | 设置
升级 | 认证

Creating new tags on a whim is forbidden.

7.4 Multi-Alias Routes and Validation ​

  • Multiple alias paths (such as /songs/{id}/play and /songs/{id}/play.m3u8) each get their own @Router line; HEAD is not listed separately
  • Catch-all routes list all actual methods; dynamic routes note their placeholder nature in @Description
  • After modifying annotations you must run make swagger to regenerate; the artifacts (docs/swagger.json, docs/swagger.yaml, docs/docs.go) must be committed
  • Validation: output contains the new @Router path + grep hits in swagger.json + visual inspection at /swagger/index.html after startup

8. Complete route inventory ​

The following inventory comes from the current docs/swagger.json and was checked against route registration. HEAD is omitted. Installed plugins determine dynamic paths; OpenAPI placeholders are not fixed business APIs.

Songs ​

PathMethods
/api/v1/songsGET
/api/v1/songs/batch-deletePOST
/api/v1/songs/cleanPOST
/api/v1/songs/duplicatesGET
/api/v1/songs/facetsGET
/api/v1/songs/foldersGET
/api/v1/songs/idsGET
/api/v1/songs/namesGET
/api/v1/songs/organizePOST
/api/v1/songs/organize/previewPOST
/api/v1/songs/radioPOST
/api/v1/songs/randomGET
/api/v1/songs/refresh-metadataPOST
/api/v1/songs/refresh-metadata/cancelPOST
/api/v1/songs/refresh-metadata/progressGET
/api/v1/songs/remotePOST
/api/v1/songs/statsGET
/api/v1/songs/{id}GET, PUT, DELETE
/api/v1/songs/{id}/activatePOST
/api/v1/songs/{id}/artistsGET, PUT
/api/v1/songs/{id}/audio-tracksGET
/api/v1/songs/{id}/coverGET
/api/v1/songs/{id}/hls/playlistGET
/api/v1/songs/{id}/hls/segmentGET
/api/v1/songs/{id}/lyricGET
/api/v1/songs/{id}/lyricsPUT
/api/v1/songs/{id}/playGET
/api/v1/songs/{id}/play.m3u8GET
/api/v1/songs/{id}/playedPOST
/api/v1/songs/{id}/song-tagsGET, PUT
/api/v1/songs/{id}/tagsPUT
/api/v1/songs/{id}/tracksGET
/api/v1/songs/{id}/video-hls/playlist.m3u8GET
/api/v1/songs/{id}/video-hls/{path}GET

Playlists ​

PathMethods
/api/v1/playlistsGET, POST
/api/v1/playlists/batch-deletePOST
/api/v1/playlists/exportGET
/api/v1/playlists/importPOST
/api/v1/playlists/reorderPUT
/api/v1/playlists/{id}GET, PUT, DELETE
/api/v1/playlists/{id}/coverGET, POST
/api/v1/playlists/{id}/pinPUT
/api/v1/playlists/{id}/song-idsGET
/api/v1/playlists/{id}/songsGET, POST
/api/v1/playlists/{id}/songs/movePUT
/api/v1/playlists/{id}/songs/reorderPUT
/api/v1/playlists/{id}/songs/sortPOST
/api/v1/playlists/{id}/songs/{songId}DELETE
/api/v1/playlists/{id}/sortPUT
/api/v1/playlists/{id}/touchPOST
/api/v1/playlists/{id}/visibilityPUT

Play history ​

PathMethods
/api/v1/play-historyGET, DELETE
/api/v1/play-history/entryDELETE

Authentication ​

PathMethods
/api/v1/auth/loginPOST
/api/v1/auth/logoutPOST
/api/v1/auth/refreshPOST
/api/v1/auth/tokensGET
/api/v1/auth/tokens/{token_id}DELETE

Generic configuration ​

PathMethods
/api/v1/configsGET, POST
/api/v1/configs/{key}GET, PUT, DELETE

Business settings ​

PathMethods
/api/v1/settings/auto-scanGET, PUT
/api/v1/settings/equalizerGET, PUT
/api/v1/settings/github-discovery-tokenGET, PUT
/api/v1/settings/github-proxyGET, PUT
/api/v1/settings/hls-proxyGET, PUT
/api/v1/settings/http-proxyGET, PUT
/api/v1/settings/library-browseGET, PUT
/api/v1/settings/log-levelGET, PUT
/api/v1/settings/music-pathGET, PUT
/api/v1/settings/plugin-auto-updateGET, PUT
/api/v1/settings/plugin-keep-aliveGET, PUT
/api/v1/settings/plugin-orderGET, PUT
/api/v1/settings/plugin-registriesGET, PUT
/api/v1/settings/proxy-private-allowlistGET, PUT
/api/v1/settings/remote-title-sourceGET, PUT
/api/v1/settings/scan-auto-create-playlistsGET, PUT
/api/v1/settings/scan-auto-fingerprintGET, PUT
/api/v1/settings/scan-playlist-modeGET, PUT
/api/v1/settings/scan-title-sourceGET, PUT
/api/v1/settings/tab-configGET, PUT
/api/v1/settings/tag-sync-to-fileGET, PUT
/api/v1/settings/theme-catalog-urlGET, PUT
/api/v1/settings/user-preferencesGET, PUT
/api/v1/settings/volume-normalizeGET, PUT

Scanning and fingerprints ​

PathMethods
/api/v1/scanPOST
/api/v1/scan/cancelPOST
/api/v1/scan/dir-namesGET
/api/v1/scan/directoriesGET
/api/v1/scan/fingerprintsPOST
/api/v1/scan/fingerprints/cancelPOST
/api/v1/scan/fingerprints/failedGET
/api/v1/scan/fingerprints/progressGET
/api/v1/scan/fingerprints/statusGET
/api/v1/scan/progressGET

Cache ​

PathMethods
/api/v1/cache-manage/cleanPOST
/api/v1/cache-manage/configGET, PUT
/api/v1/cache-manage/statsGET
/api/v1/cache-manage/validate-dirPOST

Plugin management ​

PathMethods
/api/v1/jspluginsGET
/api/v1/jsplugins/registry/installPOST
/api/v1/jsplugins/registry/refreshPOST
/api/v1/jsplugins/storage/cleanupPOST
/api/v1/jsplugins/update-allPOST
/api/v1/jsplugins/uploadPOST
/api/v1/jsplugins/{id}GET, PUT, DELETE
/api/v1/jsplugins/{id}/check-updateGET
/api/v1/jsplugins/{id}/disablePOST
/api/v1/jsplugins/{id}/enablePOST
/api/v1/jsplugins/{id}/updatePOST

Plugin runtime ​

PathMethods
/api/v1/jsplugin/{entryPath}GET
/api/v1/jsplugin/{entryPath}/files/{path}GET, HEAD
/api/v1/jsplugin/{entryPath}/staticGET
/api/v1/jsplugin/{entryPath}/static/{path}GET
/api/v1/jsplugin/{entryPath}/{path}GET, PUT, POST, DELETE

Shared plugin assets ​

PathMethods
/api/v1/jsplugin-assets/web-core/{path}GET
/api/v1/jsplugin-assets/{path}GET

Plugin health ​

PathMethods
/api/v1/plugins/healthGET

Custom tags ​

PathMethods
/api/v1/song-tagsGET, POST
/api/v1/song-tags/{id}GET, PUT, DELETE
/api/v1/song-tags/{id}/bindPOST
/api/v1/song-tags/{id}/song-idsGET
/api/v1/song-tags/{id}/songsGET
/api/v1/song-tags/{id}/unbindPOST

Theme packs ​

PathMethods
/api/v1/theme-packsGET, POST
/api/v1/theme-packs/activeGET, PUT, DELETE
/api/v1/theme-packs/catalog/installPOST
/api/v1/theme-packs/catalog/refreshPOST
/api/v1/theme-packs/{themeID}GET, DELETE

Backend upgrades ​

PathMethods
/api/v1/upgrade/checkGET
/api/v1/upgrade/progressGET
/api/v1/upgrade/resetPOST
/api/v1/upgrade/startPOST
/api/v1/upgrade/uploadPOST
/api/v1/upgrade/upload/confirmPOST
/api/v1/upgrade/versionsGET

Resource and transcode proxy ​

PathMethods
/api/v1/proxyGET
/api/v1/proxy/transcodeGET

Log export ​

PathMethods
/api/v1/logs/exportGET

Health check ​

PathMethods
/api/v1/healthGET

Version ​

PathMethods
/api/v1/versionGET